package com.jml.ArrayList;


import java.util.Arrays;

public class ExtArrayList<E>  implements ExtList<E>{


	private Object[] elementData ;
	//记录arraylist的实际大小
	private int size ;

	// 默认初始化容量10
	private static final int DEFAULT_CAPACITY = 10;

	//初始化容量大小
	public ExtArrayList(int initialCapacity) {
		if (initialCapacity < 0)
			throw new IllegalArgumentException("初始容量不能小于0");
		this.elementData = new Object[initialCapacity];
	}

	public ExtArrayList() {
		this(DEFAULT_CAPACITY);
	}

	public void add(E object){
		//1.判断实际存放的数据容量是否大于elementData
		ensureExplicitCapacity(size+1);
		//2.直接使用下标进行赋值
		elementData[size]=object;
		size++;
	}

	private void ensureExplicitCapacity(int minCapacity) {
		int oldCapacity = elementData.length;
		if(size == oldCapacity){
			int newCapacity=oldCapacity+oldCapacity>>1;
			//只有oldCapacity在等于1的时候才会实现这个if条件
			if(minCapacity>newCapacity){
				newCapacity = minCapacity;
			}
			Object[] newObjects = new Object[newCapacity];
			Object[] objects = Arrays.copyOf(elementData, newCapacity);
			/*for (int i = 0; i < elementData.length; i++) {
				newObjects[i]=elementData[i];
			}*/
			elementData = objects;
		}
	}

	public E get(int index) throws Exception {
		if(index>size){
			throw new Exception("索引越界");
		}
		return (E) elementData[index];
	}

	public int getSize(){
		return size;
	}

	//根据索引删除
	public Object remove(int index) {
		//下标查询值是否存在
		Object oldValue = elementData[index];
		fastRemove(index);
		return oldValue;
	}

	//根据对象删除
	public boolean remove(E o) {
		if (o == null) {
			for (int index = 0; index < size; index++)
				if (elementData[index] == null) {
					fastRemove(index);
					return true;
				}
		} else {
			for (int index = 0; index < size; index++)
				if (o.equals(elementData[index])) {
					fastRemove(index);
					return true;
				}
		}
		return true;
	}
	private void fastRemove(int index) {
		//如果删除的是最后一个元素就不用位移
		int numMoved = size - index - 1;
		if (numMoved > 0) {
			System.arraycopy(elementData, index + 1, elementData, index, numMoved);
		}
		//移动后将最后一个元素置为空
		elementData[--size] = null;
	}

	public void add(int index, E object) throws Exception {
		if(index>elementData.length-1){
			throw new Exception("索引越界");
		}
		//扩容
		ensureExplicitCapacity(size+1);
		int numMoved = size - index;
		if (numMoved > 0) {
			System.arraycopy(elementData, index, elementData, index + 1, numMoved);
		}
		elementData[index] = object;
		++size;
	}

}
